package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.qo.QueryObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleService implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public void saveOrUpdate(Role role, Long[] permissionIds) {
        if(role.getId() != null){
            roleMapper.updateByPrimaryKey(role);
            roleMapper.deleteRelationRoleAndPermission(role.getId());
        } else {
            roleMapper.insert(role);
        }
        if(permissionIds != null){
            for (Long permissionId : permissionIds) {
                roleMapper.insertRelationRoleAndPermission(role.getId(),permissionId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        if(id != null){
            roleMapper.deleteByPrimaryKey(id);
            roleMapper.deleteRelationRoleAndPermission(id);
            employeeMapper.deleteRelationEmployeeAndRoleByRoleId(id);
        }
    }

    @Override
    public Role getRoleById(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> getAll() {
        return roleMapper.selectAll();
    }

    @Override
    public PageInfo<Role> selectByQuery(QueryObject queryObject) {
//        int totalCount = roleMapper.countByQuery(queryObject);
//        if(totalCount == 0){
//            return new PageResult(1,queryObject.getPageSize(),0, Collections.emptyList());
//        }
        PageHelper.startPage(queryObject.getCurrentPage(),queryObject.getPageSize());
        List<Role> roles = roleMapper.selectByQuery(queryObject);
        return new PageInfo<>(roles);
    }

    @Override
    public List<String> getExpressionsByEmployeeId(Long employeeId) {

        return roleMapper.getExpressionsByEmployeeId(employeeId);
    }
}
